package mq

import (
	"gitee.com/Cookie_XiaoD/go-filestore-server/config"
	"github.com/streadway/amqp"
	"log"
	"time"
)

// 如果异常关闭，会接收通知
var notifyClose chan *amqp.Error
var innerConn *amqp.Connection
var innerChannel *amqp.Channel

func init() {
	// 是否开启异步转移功能，开启时才初始化rabbitMQ连接
	if !config.RabbitMQCfg.EnableAsyncTransfer {
		log.Println("未启用异步转移")
		return
	}
	if !initChannel() {
		return
	}
	//notifyClose 在内部，往管道里存储一次数据后，就会close
	notifyClose = make(chan *amqp.Error)
	innerChannel.NotifyClose(notifyClose)
	// 断线自动重连
	go func() {
		for {
			select {
			case msg, ok := <-notifyClose:
				if !ok {
					return
				}
				if msg == nil {
					return
				}

				log.Printf("进行重连：%v", msg)
				if innerChannel != nil {
					innerChannel.Close()
				}
				if innerConn != nil {
					innerConn.Close()
				}
				innerConn = nil
				innerChannel = nil
				for !initChannel() {
					log.Println("重连失败，5秒后重试")
					time.Sleep(5 * time.Second)
				}
				notifyClose = make(chan *amqp.Error)
				innerChannel.NotifyClose(notifyClose)
			}
		}
	}()
	log.Println("MQ初始化")
}
